<?php

namespace App\Http\Controllers;

use App\Models\Workflow\WorkflowNode;
use App\User;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class DingSendNotifyController extends Controller
{
    /**
     * 发送消息
     *
     * @param $next_node_id
     * @param $table_name
     * @param $table_id
     * @param  string  $description  您有一条待审核流程：流程名称（物资入库、物资出库、物资轮胎出库、维修申请）
     *          - 申请人 - 车牌号（维修理流程加车牌号） - 日期时间 - 单据号
     *
     * @return void
     */
    public function userNotify($next_node_id, $table_name, $table_id, $description = ''): void
    {
        if($next_node_id>0){
            $agent_id = env('Ding_Agent_Id');
            $accessToken = Cache::get('dingAccessToken');
            if (! $accessToken) {
                $this->getToken();
                $accessToken = Cache::get('dingAccessToken');
            }
            $url = 'https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token='.$accessToken;
            $role_id = WorkflowNode::query()->where('id', $next_node_id)->value('role_id');
            $role_name = DB::table('sys_roles')->where('id', $role_id)->value('name');
            if ($role_name == '物资-经手人') {
                $user_id = DB::table($table_name)->where('id', $table_id)->pluck('handler_user_id')->toArray();
            } else {
                $user_id = DB::table('sys_roles_users')->where('role_id', $role_id)->pluck('user_id')->toArray();
            }
            $ding_user_ids = User::query()->whereIn('id', $user_id)->pluck('ding_user_id')->toArray();
            $msg = json_encode([
                'msgtype' => 'link',
                'link'    => [
                    'messageUrl' => 'eapp://pages/index/index',
                    'picUrl'     => 'http://39.98.147.207:9007/images/free-background.png',
                    'title'      => '您有一条待处理流程',
                    'text'       => $description,
                ],
            ]);
            $post_data = [
                'agent_id'    => $agent_id,
                'userid_list' => implode(',', $ding_user_ids),
                'msg'         => $msg,
            ];
            $json = $this->postCurl($url, $post_data, 'post');
            file_put_contents('44.txt', $json.'^^^^'.date('Y-m-d H:i:s').'&&&'.$agent_id);
            foreach ($user_id as $v) {
                $result = DB::table('akbus_notify')
                    ->insertGetId([
                        'title'        => '您有一条待处理流程', 'description' => $description, 'user_id' => $v, 'type' => '通知',
                        'send_user_id' => 1, 'is_read' => '未读', 'is_del' => '未删除',
                        'created_at'   => date('Y-m-d H:i:s'),
                    ]);
            }
        }
    }

    // curl
    public function postCurl($url, $data, $type)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($type == 'post') {
            curl_setopt($ch, CURLOPT_POST, true);
            //设置post数据
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        $json = curl_exec($ch);
        curl_close($ch);
        return $json;
    }

    //获取钉钉token
    public function getToken()
    {
        $appKey = "dingae5wqdjvggo39hmu";
        $appSecret = "OgkK9VPA7e6MIlQXjfn59hy12Aut8BnUpEeQkNgTi81kaY62l8s6q9hZusyTJqJ7";
        $url = 'https://oapi.dingtalk.com/gettoken?appkey='.$appKey.'&appsecret='.$appSecret;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        $json = curl_exec($ch);
        curl_close($ch);
        $arr = json_decode($json, true);
        Cache::put('dingAccessToken', $arr['access_token'], 7200);
    }
}
